package com.example.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AuthorizationCheck implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(request.getRequestURI());
        System.out.println(request.getMethod());

        if (request.getRequestURI().endsWith(".js")){
            return true;
        }

        if (!request.getRequestURI().startsWith("/login") && !request.getRequestURI().startsWith("/signup") ){
            //校验Session
            HttpSession session = request.getSession();
            if (!"admin".equals(session.getAttribute("username")) || !"admin".equals(session.getAttribute("password"))){
                response.addHeader("Location","/login");
                response.setStatus(302);
                return false;
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
